package bizapi.sinosoft.com.provider.balance;

import bizapi.sinosoft.com.provider.CommonResponse;
import cms.api.ConsumeHistoryApi;
import cms.api.OrganizationApi;
import cms.model.ConsumeHistory;
import cms.model.Organization;
import com.weibo.api.motan.config.springsupport.annotation.MotanReferer;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.util.List;

/**
 * Created by xujingfeng on 2017/3/10.
 */
@RestController
@RequestMapping("api/balance")
public class BalanceRestController {

    @MotanReferer
    OrganizationApi organizationApi;
    @MotanReferer
    ConsumeHistoryApi consumeHistoryApi;

    @Value("${cyOrganizationId:3561a343-7b1f-45ee-a2b8-7e0e09ee8d00}")
    String cyOrganizationId;

    //固定页大小
    final static int pageSize = 200;

    @RequestMapping("/getBalance")
    @Transactional(readOnly = true)
    public CommonResponse<BigDecimal> getBalance() {
        CommonResponse<BigDecimal> commonResponse = new CommonResponse();
        try {
            Organization organization = organizationApi.findOrganizationById(cyOrganizationId);
            commonResponse.setResult(organization.getCurrentMoney());
            commonResponse.setSuccess(true);
            return commonResponse;

        } catch (Exception e) {
            commonResponse.setResultMessage(e.getMessage());
            commonResponse.setSuccess(false);
            return commonResponse;
        }
    }

    @RequestMapping("/getConsumeHistory")
    @Transactional(readOnly = true)
    public CommonResponse<Page<ConsumeHistory>> getConsumeHistory(Integer pageNumber) {
        CommonResponse<Page<ConsumeHistory>> commonResponse = new CommonResponse();
        try {
            Pageable pageable = new PageRequest(pageNumber, pageSize, new Sort(Sort.Direction.DESC, "dateCreated"));
            Page<ConsumeHistory> consumeHistories = consumeHistoryApi.listConsumeHistoryByOrganizationId(cyOrganizationId, pageable);
            List<ConsumeHistory> content = consumeHistories.getContent();
            for (ConsumeHistory consumeHistory : content) {
                consumeHistory.setId(null);
                consumeHistory.setMemberId(null);
                consumeHistory.setOrganization(null);
            }
            commonResponse.setResult(consumeHistories);
            commonResponse.setSuccess(true);
            return commonResponse;
        } catch (Exception e) {
            commonResponse.setResultMessage(e.getMessage());
            commonResponse.setSuccess(false);
            return commonResponse;
        }
    }


}
